import router from '@/router'
import { useUserStore } from '@/stores/userStore'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 20 * 1000,
})

// 返回值的类型
export interface ServiceResponse<T> {
  code: number
  data: T
  msg: string
}

// 封装通用的请求工具函数
export const request = <T>(url: string, method: Method = 'GET', submitData?: object) =>{
  return service.request<T,ServiceResponse<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData,
  })
}
// 请求拦截器
service.interceptors.request.use(
  config => {
    // 携带token操作
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)
// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 拦截错误并处理
    if(error.response){
      ElMessage.error(error.response.data.msg)
      if(error.response.status === 401){
        const userStore = useUserStore()
        userStore.removeToken()
        router.push("/login")
      }
    }else{
      ElMessage.error('请求超时，请稍后再试')
    }

    return Promise.reject(error)
  },
)

export default service
